import os,random
from re import sub
from config import MOVIE_TYPE
from datetime import timedelta
"""这个是底层的操作逻辑，防止目录穿越等非法数据操作，所有的底层操作都在这里，不要直接调用到中间层中"""
"""这个是底层的操作逻辑，防止目录穿越等非法数据操作，所有的底层操作都在这里，不要直接调用到中间层中"""
"""这个是底层的操作逻辑，防止目录穿越等非法数据操作，所有的底层操作都在这里，不要直接调用到中间层中"""
def get_subdir_folders(folder_path):
    """获取指定文件夹下的所有直接子文件夹名称列表"""
    if not os.path.exists(folder_path):
        return []
        
    return [
        name for name in os.listdir(folder_path)
        if os.path.isdir(os.path.join(folder_path, name))
    ]
def get_subdir_videos(folder_path):
    """获取指定文件夹下的所有直接子视频文件名称列表"""
    if not os.path.exists(folder_path):
        return []

    return [
        name for name in os.listdir(folder_path)
        if os.path.isfile(os.path.join(folder_path, name))
        and name.lower().endswith(('.mp4', '.avi', '.mkv', '.mov'))
    ]

def extractFolderStructure(folder_path):
    """提取指定文件夹下的子文件夹结构，返回二级子文件夹列表"""
    if not os.path.exists(folder_path):
        return []
    
    result = []
    # 获取一级子文件夹
    folders_temp = get_subdir_folders(folder_path)
    
    # 对每个一级子文件夹，获取其子文件夹
    for folder in folders_temp:
        subfolder_path = os.path.join(folder_path, folder)
        subfolders = get_subdir_folders(subfolder_path)
        result.append({
            "folder_name": folder,
            "subfolders": subfolders
        })
    
    return result
    
def count_folder(folder_path):
    """统计指定文件夹下的视频文件数量（不遍历）"""
    if not os.path.exists(folder_path):
        return 0
    video_ext = MOVIE_TYPE
    count = 0
    for entry in os.scandir(folder_path):
        if entry.is_file() and os.path.splitext(entry.name)[1].lower() in video_ext:
            count += 1
    return count

def get_duration(video_path):
    """获取视频文件的时长（秒）"""# 此处应该要调用ffmpeg获取视频时长，后面再说，先模拟
    if not os.path.exists(video_path):
        return 0
    return str(timedelta(seconds=random.randint(1500, 7200)))[2:]

def count_folder_walk(folder_path):
    """统计指定文件夹下的视频文件数量（递归遍历）"""
    if not os.path.exists(folder_path):
        return 0
    video_ext = MOVIE_TYPE
    count = 0
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if os.path.splitext(file)[1].lower() in video_ext:
                count += 1
    return count

#这个函数是递归当中所有的子文件夹名字，不一定会用到，但是先写了
def get_all_subdirs_recursive(folder_path):
    """递归获取所有嵌套子文件夹"""
    subdirs = []
    for root, dirs, files in os.walk(folder_path):
        subdirs.extend(dirs)
    return list(set(subdirs))  # 去重后返回

def get_folders_videos(folder_path):
    """获取指定文件夹下的所有直接子文件夹名称和视频文件名称"""
    subfolders = get_subdir_folders(folder_path)
    videos = get_subdir_videos(folder_path)
    return subfolders, videos

def count_videos_in_tree(tree):
    """递归统计树状结构中的视频总数"""
    count = len(tree.get('videos', []))
    for subfolder in tree.get('subfolders', []):
        count += count_videos_in_tree(subfolder)
    return count

def get_folders_videos_walk(folder_path):
    """获取指定文件夹下的所有子文件夹名称和视频文件名称（递归遍历）"""
    if not os.path.exists(folder_path):
        return [], []
        
    subfolders = []
    videos = []
    
    for root, dirs, files in os.walk(folder_path):
        # 计算相对路径
        rel_path = os.path.relpath(root, folder_path)
        if rel_path != '.':  # 排除根目录自身
            subfolders.append(rel_path)
            
        # 处理视频文件
        for file in files:
            if any(file.lower().endswith(ext) for ext in ('.mp4', '.avi', '.mkv', '.mov')):
                # 构建相对路径
                if rel_path == '.':
                    videos.append(file)
                else:
                    videos.append(os.path.join(rel_path, file))
                    
    return subfolders, videos

def get_folders_videos_tree(folder_path):
    """获取文件夹树状结构，每个节点包含子文件夹和视频信息"""
    if not os.path.exists(folder_path):
        return {"folder_name": os.path.basename(folder_path), "videos": [], "subfolders": []}
    
    result = {
        "folder_name": os.path.basename(folder_path),
        "videos": [],
        "subfolders": []
    }
    
    # 获取当前目录下的视频
    videos = get_subdir_videos(folder_path)
    result["videos"] = videos
    
    # 获取并处理子文件夹
    subfolders = get_subdir_folders(folder_path)
    for subfolder in subfolders:
        subfolder_path = os.path.join(folder_path, subfolder)
        # 递归获取子文件夹的树状结构
        subfolder_tree = get_folders_videos_tree(subfolder_path)
        result["subfolders"].append(subfolder_tree)
    
    return result



if __name__ == "__main__":
    import os
    
    # 测试准备
    test_dir = "./movies"
    os.makedirs(os.path.join(test_dir, "web/test003"), exist_ok=True)
    os.makedirs(os.path.join(test_dir, "pwn/test001"), exist_ok=True)
    
    # 测试get_subdir_folders
    print("=== 一级子文件夹测试 ===")
    subdirs = get_subdir_folders(test_dir)
    print(f"找到{len(subdirs)}个一级子文件夹：{subdirs}")
    
    # 测试extractFolderStructure
    print("\n=== 二级子文件夹结构测试 ===")
    structure = extractFolderStructure(test_dir)
    print(subdirs)
    print(structure)
    # for item in structure:
    #     print(f"{item['folder_name']} => 子文件夹：{item['subfolders']}")

